package com.example.smartagrisys.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件存储配置
 * 启动时自动创建上传目录
 */
@Slf4j
@Component
public class FileStorageConfig implements CommandLineRunner {

    @Value("${file.upload.path:./uploads/}")
    private String uploadPath;

    @Override
    public void run(String... args) {
        try {
            // 确保上传目录存在
            Path rootPath = getUploadRootPath();
            Files.createDirectories(rootPath);
            log.info("创建上传根目录成功: {}", rootPath.toAbsolutePath());
            
            // 创建产品图片目录
            Path productDir = rootPath.resolve("product");
            Files.createDirectories(productDir);
            log.info("创建产品图片目录成功: {}", productDir.toAbsolutePath());
            
            log.info("文件存储路径准备完毕: {}", rootPath.toAbsolutePath());
        } catch (Exception e) {
            log.error("创建文件存储目录失败", e);
        }
    }
    
    /**
     * 获取上传根目录的绝对路径
     */
    private Path getUploadRootPath() {
        String path = uploadPath;
        
        // 如果以./开头，则基于当前用户目录处理
        if (path.startsWith("./")) {
            path = System.getProperty("user.dir") + path.substring(1);
        } 
        // 如果不是绝对路径，则基于用户目录创建绝对路径
        else if (!path.startsWith("/") && !path.matches("^[A-Za-z]:\\\\.*")) {
            path = System.getProperty("user.dir") + File.separator + path;
        }
        
        Path rootPath = Paths.get(path);
        log.info("上传根目录的绝对路径: {}", rootPath.toAbsolutePath());
        return rootPath;
    }
} 